package modules.fin.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import luxing.common.service.impl.CommonServiceImpl;
import luxing.util.DateUtil;
import luxing.util.LoginUserUtil;
import modules.fin.entity.IncomeUnit;
import modules.fin.entity.IncomeUnitSum;
import modules.fin.service.IncomeUnitService;

/**
 * 
 * @author zzc
 *
 */
@Service("incomeUnitService")
@Transactional
public class IncomeUnitServiceImpl extends CommonServiceImpl implements IncomeUnitService {

	public void settle(IncomeUnitSum incomeUnitSum) {
		save(incomeUnitSum);
		for (IncomeUnit incomeUnit : incomeUnitSum.getIncomeUnitList()) {
			incomeUnit.setIncomeUnitSum(incomeUnitSum);
			saveOrUpdate(incomeUnit);
		}
	}

	public void doVoid(IncomeUnitSum incomeUnitSum) {
		for (IncomeUnit incomeUnit : incomeUnitSum.getIncomeUnitList()) {
			incomeUnit.setIncomeUnitSum(null);
			incomeUnit.setStatus(IncomeUnit.STATUS_NO);
			incomeUnit.setSettleBy(null);
			incomeUnit.setSettleDate(null);
			super.saveOrUpdate(incomeUnit);
		}
		super.saveOrUpdate(incomeUnitSum);
	}

	public List<IncomeUnit> listByUnitAndExpensesAndStatus(String unit, String expensesId, String status) {
		String hql = "from IncomeUnit where unit=? and expenses.id=? and status=? and tenantId=?";
		return listByHql(hql, unit, expensesId, status, LoginUserUtil.getLoginUser().getTenantId());
	}

	public List<IncomeUnit> listByExpenses(String expensesId) {
		String hql = "from IncomeUnit where expenses.id=?  and tenantId=?";
		return listByHql(hql, expensesId, LoginUserUtil.getLoginUser().getTenantId());
	}

	public String getSn() {
		String hql = "from IncomeUnitSum where date(createDate)=? and tenantId=? order by sn desc";
		List<IncomeUnitSum> incomeUnitSumList = listByHql(hql, new Date(), LoginUserUtil.getLoginUser().getTenantId());
		String sn = "SDWK" + DateUtil.dateToStr(new Date(), "yyyyMMdd") + "001";
		if (CollectionUtils.isNotEmpty(incomeUnitSumList)) {
			String endNum = incomeUnitSumList.get(0).getSn().substring(12, 15);
			if (StringUtils.isNumeric(endNum)) {
				endNum = String.valueOf(Integer.valueOf(endNum).intValue() + 1);
				if (endNum.length() == 1) {
					endNum = "00" + endNum;
				} else if (endNum.length() == 2) {
					endNum = "0" + endNum;
				}
				sn = "SDWK" + DateUtil.dateToStr(new Date(), "yyyyMMdd") + endNum;
				return sn;
			}
		}
		return sn;
	}

}
